<?php
//DB.php
//Singlton DB
//DB::connect()->...

class DB extends QueryBuilder
{
	protected static $connect;
	protected static $pdo;	
	
	private function __construct()
	{
	
	}
	public static function connect()
	{
		if(is_null(self::$connect))
		{
			self::$connect = new DB();
			try
			{
				if(DB::$pdo = new PDO(DB_USE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD))
				{
				
				}
				else
				{
					throw new Exception('PDO error message: '.$e->getMessage());
				}
				
			}
			catch(PDOException $e)
			{
				throw new Exception('PDO error message: '.$e->getMessage());
			}
		}
		return self::$connect;
	}
	
	//Univers method for query PDO
	public function query()
	{
		if(isset($this->query) && !empty($this->query))
		{
			try
			{
				$result =  DB::$pdo->exec($this->getQuery());
				
				if(isset($this->query['insert']))
				{
					
					$lastId = DB::$pdo->lastInsertId();
					
					return $lastId;
				}
				elseif($result)
				{
					return $result;
				}
				else
				{
					return false;
				}	
			}
			catch (PDOException $e)
			{
				throw new Exception('PDO error message: '.$e->getMessage());	
			}	
		}
	}
	
	//Get one row from table	
	public function getRow()
	{
		if(isset($this->query) && !empty($this->query))
		{	
			try
			{
				$res = DB::$pdo->query($this->getQuery());
				if($res)
				{
					$result = $res->fetchAll(PDO::FETCH_ASSOC);
					if(!empty($result))
					{
						return $result[0];
					}
				}			
				else
				{
					return false;
				}	
			}
			catch (PDOException $e)
			{
				throw new Exception('PDO error message: '.$e->getMessage());	
			}
		}
	}

	//Get all rows from table	
	public function getAll()
	{
		if(isset($this->query) && !empty($this->query))
		{	
			try
			{
				$res = DB::$pdo->query($this->getQuery());
				if($res)
				{
					$result = $res->fetchAll(PDO::FETCH_ASSOC);
				}
				else
				{
					throw new Exception('DB error. Please check database settings.');
				}	
				if($result)
				{
					return $result;	
				}
				else
				{
					return false;
				}				
			}
			catch (PDOException $e)
			{
				throw new Exception('PDO error message: '.$e->getMessage());	
			}
		}
	}
}